


#include "Triangle.hpp"
#include "rasterizer.hpp"
#include <eigen3/Eigen/Eigen>
#include <iostream>
#include <opencv2/opencv.hpp>

constexpr double MY_PI = 3.1415926;

Eigen::Matrix4f get_view_matrix(Eigen::Vector3f eye_pos)
{
    Eigen::Matrix4f view = Eigen::Matrix4f::Identity();//初始化为单位矩阵

    Eigen::Matrix4f translate;
    translate << 1, 0, 0, -eye_pos[0], 0, 1, 0, -eye_pos[1], 0, 0, 1,
        -eye_pos[2], 0, 0, 0, 1;

    view = translate * view;

    return view;
}

Eigen::Matrix4f get_model_matrix(float rotation_angle)
{
    Eigen::Matrix4f model = Eigen::Matrix4f::Identity();

    // TODO: Implement this function
    // Create the model matrix for rotating the triangle around the Z axis.
    // Then return it.
    const float cos_alpha = std::cos(rotation_angle);
    const float sin_alpha = std::sin(rotation_angle);

    model << cos_alpha, -sin_alpha, 0, 0,
            sin_alpha, cos_alpha, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1; 

    return model;
}

Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
                                      float zNear, float zFar)
{
    // Students will implement this function

    Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();

    // TODO: Implement this function
    // Create the projection matrix for the given parameters.
    // Then return it.
    Eigen::Matrix4f M_persp_to_ortho;
    Eigen::Matrix4f M_translation;
    Eigen::Matrix4f M_scale;

    M_persp_to_ortho << zNear, 0, 0, 0,
                        0, zNear, 0, 0,
                        0, 0, zNear+zFar, -zNear*zFar,
                        0, 0, 1, 0;

    M_translation << 1, 0, 0, 0,
                    0, 1, 0, 0,
                    0, 0, 1, -(zNear+zFar)/2,
                    0, 0, 0, 1;
    
    const float PI = acos(-1);
    float halfAngle = eye_fov / 2 / 180 * PI;
    float height = -zNear * tan(halfAngle);
    float width = height * aspect_ratio;

    M_scale << 1/width, 0, 0, 0,
                0, 1/height, 0, 0,
                0, 0, 1/(zNear-zFar), 0,
                0, 0, 0, 1;

    projection = M_scale * M_translation * M_persp_to_ortho;
    
    return projection;
}

int main(int argc, const char** argv)
{
    // argc: 表示传入的参数的数量
    // argv: 这是一个字符指针数组，存储了所有传入的参数
    // argv[0]是程序的名称， 后续的元素(如argv[1], argv[2])是用户输入的参数


    // 这里简单模拟一个图形管线
    float angle = 0;
    bool command_line = false;
    std::string filename = "output.png";

    if (argc >= 3) { //如果传入了至少三个参数，
    // 也就是程序名 + 至少两个用户参数
        command_line = true; //设置flag
        angle = std::stof(argv[2]); // -r by default
        //把第三个参数 转换成浮点数赋值给angle
        if (argc == 4) { //检查是否有第四个参数文件名
        // 如果有 就赋值给filename，如果没有 就返回0 结束
            filename = std::string(argv[3]);
        }
        else
            return 0;
    }

    // 定义了光栅化器的实例，然后设置了其必要的变量
    // 然后我们得到一个带有三个顶点的硬编码三角形

    rst::rasterizer r(700, 700);

    Eigen::Vector3f eye_pos = {0, 0, 5};

    std::vector<Eigen::Vector3f> pos{{2, 0, -2}, {0, 2, -2}, {-2, 0, -2}};

    std::vector<Eigen::Vector3i> ind{{0, 1, 2}};

    auto pos_id = r.load_positions(pos);
    auto ind_id = r.load_indices(ind);

    int key = 0;
    int frame_count = 0;

    // 在主函数上，我们定义了三个分别计算模型、视图和投影矩阵的函数，
    // 每一个函数都会返回相应的矩阵。
    // 接着，这三个函数的返回值会被 set_model(),set_view() 和 set_projection() 三个函数传入光栅化器中。
    // 最后，光栅化器rasterizer在屏幕上显示出变换的结果。
    
    if (command_line) {
        r.clear(rst::Buffers::Color | rst::Buffers::Depth);

        r.set_model(get_model_matrix(angle));
        r.set_view(get_view_matrix(eye_pos));
        r.set_projection(get_projection_matrix(45, 1, 0.1, 50));

        r.draw(pos_id, ind_id, rst::Primitive::Triangle);
        cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
        image.convertTo(image, CV_8UC3, 1.0f);

        cv::imwrite(filename, image);

        return 0;
    }

    while (key != 27) {
        r.clear(rst::Buffers::Color | rst::Buffers::Depth);

        r.set_model(get_model_matrix(angle));
        r.set_view(get_view_matrix(eye_pos));
        r.set_projection(get_projection_matrix(45, 1, 0.1, 50));

        r.draw(pos_id, ind_id, rst::Primitive::Triangle);

        cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data());
        image.convertTo(image, CV_8UC3, 1.0f);
        cv::imshow("image", image);
        key = cv::waitKey(10);

        std::cout << "frame count: " << frame_count++ << '\n';

        if (key == 'a') {
            angle += 0.1;
        }
        else if (key == 'd') {
            angle -= 0.1;
        }
    }

    return 0;
}
